<template>
  <el-dialog :title="title" :visible="isShowDept" :before-close="handleClose" @open="getEmployeeSimple" @close="chongzhiForm">
    <!-- 匿名插槽 -->
    <el-form ref="addFormDept" v-loading="this.$store.state.logoing" :model="form" :rules="formVerify" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in list" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="addDept">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getEmployeeSimpleAPI } from '@/api/employees'
import { reqAddDepartmentsAPI, reqGetDepartDetailAPI, reqUpdateDepartmentsAPI } from '@/api/departments'
export default {
  name: 'AddDept',
  props: {
    isShowDept: {
      type: Boolean,
      required: true
    },
    bumenId: {
      type: String,
      required: true
    },
    dlist: {
      type: Array,
      required: true
    },
    addDeptType: {
      type: String,
      required: true
    }

  },
  data () {
    const validateName = (rule, value, callback) => {
      const subDepts = this.dlist.filter(item => {
        if (this.addDeptType === 'add') {
          return item.pid === this.bumenId
        } else if (this.addDeptType === 'sub') {
          return item.pid === this.form.pid && item.id !== this.form.id
        }
      })
      const flag = subDepts.some(item => {
        return item.name === value
      })
      if (flag) {
        callback(new Error('部门不能重复'))
      } else {
        callback()
      }
    }
    const validateCade = (rule, value, callback) => {
      const isok = this.dlist.some(item => {
        if (this.addDeptType === 'add') {
          return item.code === value
        } else if (this.addDeptType === 'sub') {
          return item.code === value && item.id !== this.form.id
        }
      })
      if (isok) {
        callback(new Error('code码不能重复'))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '', // 部门介绍
        id: ''
      },
      formVerify: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateName, trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateCade, trigger: ['blur', 'change'] }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      list: []
    }
  },
  computed: {
    title () {
      return this.addDeptType === 'add' ? '添加部门' : '编辑部门'
    }
  },
  methods: {
    handleClose () {
      // 通知父组件关闭弹窗
      this.$emit('update:isShowDept', false)
    },
    // 添加 子部门
    addDept () {
      this.$refs.addFormDept.validate(async valid => {
        if (valid) {
          try {
            let ret
            if (this.addDeptType === 'add') {
              ret = await reqAddDepartmentsAPI({
                ...this.form,
                pid: this.bumenId
              })
            } else if (this.addDeptType === 'sub') {
              ret = await reqUpdateDepartmentsAPI({
                ...this.form,
                pid: this.bumenId

              })
            }
            this.$emit('upDateLoad')
            this.handleClose()
            this.$message.success(ret.message)
          } catch {
            this.$message.error('未知的网络错误')
          }
        }
      })
    },
    async getEmployeeSimple () {
      if (this.addDeptType === 'sub') {
        try {
          const retq = await reqGetDepartDetailAPI(this.bumenId)
          this.form = retq.data
        } catch (err) {
          console.dir(err)
        }
      }
      const ret = await getEmployeeSimpleAPI()
      this.list = ret.data
    },
    chongzhiForm () {
      this.$refs.addFormDept.resetFields()
    }
  }
}
</script>
